package com.lenovo.testreport.user.service;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;


/**
 * @Descpription
 * @Author CJF
 * @Date 2019/1/21 12:21
 **/
@Service
public class RedisUserServiceImpl implements RedisUserService {
    @Autowired
    RedisTemplate redisTemplate;
    final static String key = "user_info_table";
    private static final Logger logger = LoggerFactory.getLogger(RedisUserServiceImpl.class);
    private RedisSerializer serializer = new StringRedisSerializer();

    @Override
    public boolean addUser(Integer uid, String SessionId, HttpServletRequest request) {
        try {
            redisTemplate.setKeySerializer(serializer);
            redisTemplate.setHashKeySerializer(serializer);
            redisTemplate.setHashValueSerializer(serializer);
            redisTemplate.opsForHash().put(key, String.valueOf(uid), SessionId);
            logger.info("AddUser###########uid:" + uid + "#########SessionId:" + SessionId + "#########IP:" + getRemortIP(request));
            return true;
        } catch (Exception e) {
            logger.error(e.toString());
            return false;
        }
    }

    static public String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    @Override
    public boolean deleteUser(Integer uid) {
        try {
            redisTemplate.setKeySerializer(serializer);
            redisTemplate.setHashKeySerializer(serializer);
            redisTemplate.setHashValueSerializer(serializer);
            String SessionId = (String) redisTemplate.opsForHash().get(key, String.valueOf(uid));
            redisTemplate.delete(SessionId);
            redisTemplate.opsForHash().delete(String.valueOf(uid));
            logger.info("DeleteUser###########uid" + uid + "#########SessionId" + SessionId);
            return true;
        } catch (Exception e) {
            logger.error(e.toString());
            return false;
        }
    }

    @Override
    public String getUserSessionID(Integer uid) {
        redisTemplate.setKeySerializer(serializer);
        redisTemplate.setHashKeySerializer(serializer);
        redisTemplate.setHashValueSerializer(serializer);
        return (String) redisTemplate.opsForHash().get(key, String.valueOf(uid));
    }

}
